package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;


    // 查询购物车列表
    @Override
    public List<Address> addressList() {
        // 1.构建条件
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        // SELECT * FROM `address_book` WHERE user_id = 1458310743471493121
        wrapper.eq(Address::getUserId, UserHolder.get().getId());
        // 2.查询并返回
        return addressMapper.selectList(wrapper);
    }
//新增地址
    @Override
    public void save(Address address) {
        //1.新增地址
        address.setUserId(UserHolder.get().getId());
        //2.mapper保存
        addressMapper.insert(address);
    }
//修改默认地址
    @Override
    public void setDefault(Long id) {
//1.把当前用户所有地址设置为默认
        //1.1准备实体
        Address address1 = new Address();
        address1.setIsDefault(0);
        //1.2构造条件
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());
        //1.3条件更新
        addressMapper.update(address1, wrapper);
        //---------------------------------------------------
        //2.把当前位置设置为默认
        //2.1准备实体
        Address address2 = new Address();
        address2.setId(id);
        address2.setIsDefault(1);
        //主键更新
        addressMapper.updateById(address2);
    }
//查询用户默认收货地址
@GetMapping("/address/default")

    @Override
    public Address findDefault() {
//构建条件
    LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(Address::getUserId, UserHolder.get().getId());
    wrapper.eq(Address::getIsDefault, 1);
    //2.查询
    return addressMapper.selectOne(wrapper);

}
//回显地址
    @Override
    public Address findAddressId(Long id) {
        //查询地址信息
        Address address = addressMapper.selectById(id);
        return address;

    }
//修改地址
    @Override
    public void updateAddress(Address address) {
        addressMapper.updateById(address);
    }
    //删除地址
    @Override
    public void deleteBatchId(List<Long> ids) {
        addressMapper.deleteBatchIds(ids);

    }



}
